/**
 * Created by wlh on 16/3/11.
 */

var React = require("react");
var ReactDom = require("react-dom");

var TLD = {};

TLD.TaskSubmitBox = React.createClass({
    displayName: "TaskSubmitBox",
    getInitialState: function () {
        return {
            val: this.props.val || '测试任务'
        }
    },
    handleSubmit: function(e) {
        e.preventDefault();
        var value = this.refs.taskContent.value;
        if (!value) {
            return false;
        }
        this.refs.taskContent.value = '';
        this.props.onAddTask({content: value});
    },
    render: function() {
        return (
            <form>
                <label htmlFor="taskContent">添加任务:<input type="text" ref="taskContent" className="form-control"/></label>
                <input type="submit" value="提交" onClick={this.handleSubmit}/>
            </form>
        )
    },
});

TLD.TaskList = React.createClass({
    displayName: "TaskList",
    getInitialState: function() {
        return {
            tasks: this.props.tasks || [],
            onRemoveTask: this.props.onRemoveTask || function() {}
        }
    },
    removeTask: function(e) {
        this.props.onRemoveTask(e.target.attributes.data.value);
    },
    render: function() {
        var self = this;
        var tasks = this.state.tasks.map(function(task, index) {
            return <li id={"li-"+index}key={Math.random()}>{task.content}&nbsp;&nbsp;<input type="button" onClick={self.removeTask} value="删除" data={index}/></li>
        });

        if (!tasks || !tasks.length) {
            tasks = <li>任务列表暂时为空!</li>
        }
        return (
            <div>
                <h6>任务列表</h6>
                <hr/>
                <ul>{tasks}</ul>
            </div>
        )
    }
});

TLD.TaskContainer = React.createClass({
    display: "TaskContainer",
    getInitialState: function() {
        return {
            tasks: []
        }
    },
    render: function() {
        return (
            <div>
                <TLD.TaskSubmitBox val="明天还要加班" onAddTask={this.handleAddTask}></TLD.TaskSubmitBox>
                <TLD.TaskList tasks={this.state.tasks} onRemoveTask={this.handleRemoveTask}></TLD.TaskList>
            </div>
        )
    },
    handleAddTask: function(task) {
        var tasks = this.state.tasks;
        tasks.push(task);
        this.setState({tasks: tasks});
    },
    handleRemoveTask: function(idx) {
        var tasks = this.state.tasks;
        delete tasks[idx];
        this.setState({tasks: tasks});
    }
});

ReactDom.render(<TLD.TaskContainer></TLD.TaskContainer>, document.getElementById("taskContainer"));